package com.credit.service;

import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchDataTransform;
import org.springside.modules.persistence.SearchFilter;

import com.credit.entity.CreditCoinRecord;
import com.credit.entity.CreditCouponEntity;
import com.credit.repository.CreditCouponDao;

@Service
@Transactional
public class CreditCouponService {
	@Autowired
    private CreditCouponDao creditCouponDao;
	
	public Page<CreditCouponEntity> getMyCouponListPage(Map<String, Object> searchParams, int pageNumber,
			Integer pageSize, String sortType, Map<String, SearchDataTransform> dataTyps) {
		
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		if (dataTyps != null) {
			SearchDataTransform.dateTypeTransform(filters, dataTyps);
		}
		Specification<CreditCouponEntity> spec = DynamicSpecifications.bySearchFilter(filters.values(), CreditCouponEntity.class);
		return creditCouponDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pageSize, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		} else {
			sort = new Sort(Direction.DESC, sortType);
		}
		return new PageRequest(pageNumber - 1, pageSize, sort);
	}

	public Integer getCouponCountByUserId(Long userId) {
		
		return creditCouponDao.getCouponCountByUserId(userId);
	}
}
